package com.ada.zip;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Apps {

    public static void main(String[] args) {
        String password = "1234567812345678";
        try {

            String zipFilePath = "E:\\data\\encrypted.zip";
            String sourceFilePath = "E:\\data\\demo\\a.txt";

            try {
                FileOutputStream fos = new FileOutputStream(zipFilePath);
                ZipOutputStream zipOut = new ZipOutputStream(fos);

                FileInputStream fis = new FileInputStream(sourceFilePath);
                ZipEntry zipEntry = new ZipEntry("file_to_encrypt.txt");
                zipOut.putNextEntry(zipEntry);

                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zipOut.write(bytes, 0, length);
                }

                fis.close();
                zipOut.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }



            FileInputStream fis = new FileInputStream(zipFilePath);
            FileOutputStream fos = new FileOutputStream("E:\\data\\encrypted_output.zip");

            SecretKeySpec secretKeySpec = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            CipherOutputStream cos = new CipherOutputStream(fos, cipher);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                cos.write(bytes, 0, length);
            }

            fis.close();
            cos.close();
            fos.close();
        } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            e.printStackTrace();
        }

    }
}
